/******************************************************************************************************
Copyright (C) 2019 Mestrelab Research S.L. All rights reserved.

This file is part of the MNova scripting toolkit.

Authorized users of MNova Software may use this file freely, but this file is provided AS IS
with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE.
*****************************************************************************************************/

/*globals NMRSpectrum, Env, mainWindow, Dir, File, TextStream, mnWarning, serialization, NMReDATAImporter*/
/*jslint plusplus: true, indent: 4*/

/** Default constructor of the converter
 * Defines the file filter
*/
function NMReDATAOpener() {
	"use strict";
}


NMReDATAOpener.importItems = function (aFileName) {
	"use strict";

	var importer, result;

	importer = new NMReDATAImporter(aFileName);
	result = importer.importNMReDATA();
	return result;
};


NMReDATAOpener.importFolder = function (aPath) {
	"use strict";

	var importer, result;

	importer = new NMReDATAImporter(aPath);
	result = importer.importNMReDATA();
	return result;
};


NMReDATAOpener.wantsImport = function (aPath) {
	"use strict";

	var i, j, dir, sdfFiles, file, stream, line;

	dir = new Dir(aPath);
	if (!dir || !dir.exists) {
		return;
	}

	sdfFiles = dir.entryListAdv("*.sdf", Dir.Name, Dir.Name);
	if (!sdfFiles || !sdfFiles.length) {
		sdfFiles = dir.entryListAdv("*/*.sdf", Dir.Name, Dir.Name);
		if (!sdfFiles || !sdfFiles.length) {
			sdfFiles = dir.entryListAdv("*/*/*.sdf", Dir.Name, Dir.Name);
		}
	}

	if (!sdfFiles || !sdfFiles.length) {
		return;
	}

	for (i = 0; i < sdfFiles.length; i++) {
		file = new File(sdfFiles[i]);
		file.open(File.ReadOnly);
		stream = new TextStream(file);
		for (j = 0; j < 300; j++) {
			line = stream.readLine();
			if (line.indexOf("NMREDATA_VERSION") !== -1) {
				return true;
			}
		}
		file.close();
		mnWarning("SDF file" + sdfFiles[i] + " has no NMReDATA version tag in the first 300 lines");
	}
	return false;
};


/** Add to the Env.Converters environment engine
 */
Env.Converters.push(new NMReDATAOpener());

//test
function testNMReDATAOpener() {
	"use strict";
	var i,
		testPaths = [
			"C:/Users/mitch/Desktop/Issues/NMReDATA/Feature15318/1-2-dihydronaphthalene.zip",
			"C:/Users/mitch/Desktop/Issues/NMReDATA/Feature15318/Menthol_full_assignments_including_2D_diag.zip",
			"C:/Users/mitch/Desktop/Issues/NMReDATA/Feature15318/bmse000168_simulation_1_nmredata.zip",
			"C:/Users/mitch/Desktop/Issues/NMReDATA/Feature15318/bmse000005_simulation_1_nmredata.zip",
			"C:/Users/mitch/Desktop/Issues/NMReDATA/Feature15318/a-b-glucose.zip"
		];

	for (i = 0; i < testPaths.length; i++) {
		serialization.open(testPaths[i]);
	}

}
